//
//  recordingViewController.m
//  test
//
//  Created by Ruj on 11/16/13.
//  Copyright (c) 2013 Ruj. All rights reserved.
//

#import "recordingViewController.h"
#import <math.h>

@interface recordingViewController ()

@end

@implementation recordingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)recordingButtonTouch:(UIButton *)sender {
    NSString* recordString = @"Record";
    
    // Get database
    Database *database = [Database getSharedInstance];
    
    if([sender.titleLabel.text isEqualToString:recordString]){
        
        // Clear old location manager;
        if(locationManager != nil){
            [locationManager stopUpdatingLocation];
            locationManager = nil;
        }
        
        currentRecordID = [database createRecord:[NSDate date]];
        
        //Start GPS and accelerometer process
        BOOL ok = [CLLocationManager locationServicesEnabled];
        if (!ok) {
            NSLog(@"oh well");
            return;
        }
        CLAuthorizationStatus auth = [CLLocationManager authorizationStatus];
        if (auth == kCLAuthorizationStatusRestricted ||
            auth == kCLAuthorizationStatusDenied) {
            NSLog(@"sigh");
            return;
        }
        
        // Set up location manager
        CLLocationManager* lm = [CLLocationManager new];
        locationManager = lm;
        locationManager.delegate = self;
        locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        locationManager.distanceFilter = 10; // 10 Meters move then update
        
        // Start accele
        motionManager = [CMMotionManager new];
        //if (!motionManager.accelerometerAvailable) {
        //    NSLog(@"oh well");
        //    return;
        //}
        motionManager.accelerometerUpdateInterval = .25;
        
        // Start location manager
        [locationManager startUpdatingLocation];
        // Start motion manager
        [motionManager startAccelerometerUpdates];
        
        // Queue accelerometer for update.
        timer = [NSTimer
                 scheduledTimerWithTimeInterval:motionManager.accelerometerUpdateInterval
                 target:self selector:@selector(pollAccel:) userInfo:nil repeats:YES];
        
        // Tell user we started recording
        [sender setTitle: @"Stop"forState:UIControlStateNormal];
        
    }else{
        // Stop recording
        if(locationManager != nil){
            [locationManager stopUpdatingLocation];
            locationManager = nil;
            
            // Stop timer
            [timer invalidate];
            
            [motionManager stopAccelerometerUpdates];
            motionManager = nil;
            
            
        }
        
        [sender setTitle: recordString forState:UIControlStateNormal];
    }

    
}


- (void)pollAccel:(NSTimer *)timer{
    if(currentRecordID > 0){
        
        //CMAccelerometerData *data = motionManager.accelerometerData;
        
        CMAccelerometerData *data = [CMAccelerometerData new];
        
        if(data != nil){
            CMAcceleration acc; //= data.acceleration;
            acc.x = (double)(arc4random()%1000) / (double)1000;
            acc.y = (double)(arc4random()%1000) / (double)1000;
            acc.z = (double)(arc4random()%1000) / (double)1000;
            
            // Get total force
            double force = acc.x * acc.x;
            force += acc.y * acc.y;
            force += acc.z * acc.z;
            force = sqrt(force);
            
            // Get current position
            if(locationManager != nil){
                // Store data in database
                Database* db = [Database getSharedInstance];
                
                [db saveRecordData:currentRecordID
                         timestamp:[NSDate date]
                          location:locationManager.location
                             force:force];
            }
        }
    }
}

// Delegate message handler for Location

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
    // Fail stop recording
    [locationManager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    // Get the lastest data, but we are not using it here as we record data in time interval
    // currentLocation = (CLLocation*)locations.lastObject;
}

@end
